#include "head.h"

void *handler(void *argv){
    threadPoolT *pool = (threadPoolT*)argv;
    while(1){
        pthread_mutex_lock(&pool->mutex);
        // 查看任务队列是否有数据
        while(pool->workQueue->len == 0){
            pthread_cond_wait(&pool->cond, &pool->mutex);
        }
        // 有数据了
        /* printf("socketfd = %d\n", pool->workQueue->head->workfd); */
        /* printQueue(pool->workQueue); */
        
        /* printf("queue len = %d\n", pool->workQueue->len); */

        int connectfd = pool->workQueue->head->workfd;
        deQueue(pool->workQueue);
        
        /* printf("queue len = %d\n", pool->workQueue->len); */
        
        pthread_mutex_unlock(&pool->mutex);

        // 密码验证
        int ret = 0;
        char userName[20]= {0};
        while((ret = loginVerify(connectfd, userName))){
            if(ret == 1){
                char mess[128] = "用户名错误";
                TLVResponse(connectfd, mess, IS_NOT_OK);
            }
            if(ret == 2){
                char mess[128] = "密码错误";
                TLVResponse(connectfd, mess, IS_NOT_OK);
            }
            if(ret == -1){
                printf("用户断开连接\n");
                perror("mess");
                break;
            }
        }
        if(ret == -1){
            close(connectfd);
            continue;
        }
        // 身份验证成功
        char mess[256] = "身份验证成功";
        TLVResponse(connectfd, mess, IS_OK);
        
        // 相关服务
        /* interactWithTheClient(connectfd); */
        
        user_t user;
        bzero(&user, sizeof(user_t));
    
        user.depth = 0;
        memcpy(user.username, userName, strlen(userName));
        user.sockfd = connectfd;
        user.slash[0] = strlen(user.username);

        strcpy(user.usercur, user.username);
        
        while(1){
            acceptOrder(&user);
        }

        close(connectfd);
    }
}

int makeThreadPool(threadPoolT *pool, int workerCount){
    
    // 初始化
    pthread_mutex_init(&pool->mutex, NULL);
    pthread_cond_init(&pool->cond, NULL);

    pool->workQueue = (workqueue_t *)calloc(1, sizeof(workqueue_t));
 
    pool->tidArr.len = workerCount;
    pool->tidArr.workerPid = (int *)calloc(workerCount, sizeof(int));

    for(int i = 0; i < workerCount; i++){
        pthread_t wPid;
        pthread_create(&wPid, NULL,handler, pool);    

        pool->tidArr.workerPid[i] = wPid;
        printf("create son thread : %lu\n", wPid);
    }
    return 0;
}
